package orm

import (
	"fmt"
	"gitee.com/dreamwood/ez"
	"strings"
)

func (this *QueryBuilder) getJoinCount() int {
	this.joinCount++
	return this.joinCount
}
func (this *QueryBuilder) getJoinAlis(key string) (alis string, field string) {
	key = ez.SnakeString(key)
	fields := strings.Split(key, ".")
	if len(fields) == 1 {
		return this.Root.GetTableName(), key
	}
	tables := make([]string, 0)
	for i, f := range fields {
		if i == len(fields)-1 {
			//最后一项是参数不是join表
			field = f
			break
		}
		tables = append(tables, f)
	}
	alis, ok := this.joinsAlis[strings.Join(tables, ".")]
	if !ok {
		return this.createJoin(key)
	}
	return alis, field
}

func (this *QueryBuilder) createJoin(key string) (alis string, field string) {
	//取出表达式//user.group__gt
	key = ez.SnakeString(key)
	fields := strings.Split(key, ".")
	if len(fields) == 1 {
		field = key
		return this.Root.GetTableName(), field
	}
	root := this.Root
	from := this.Root.GetTableName()
	alis = ""
	tables := make([]string, 0)
	for i, f := range fields {
		if i == len(fields)-1 {
			//最后一项是参数不是join表
			//return alis,f
			field = f
			break
		}
		relationConfig := root.GetRelation(f)
		//先检查是否已经存在这个join
		tables = append(tables, f)
		as, ok := this.joinsAlis[strings.Join(tables, ".")]
		if !ok {
			alis = fmt.Sprintf("t_%d", this.getJoinCount())
			this.joinsAlis[strings.Join(tables, ".")] = alis
			joins := relationConfig.CreateJoinOn(from, alis)
			for _, join := range joins {
				this.Tx.Joins(join)
			}
		} else {
			alis = as
		}
		from = alis
		root = relationConfig.Config()
	}
	return alis, field
}
